import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.net.*;
import java.io.*;;
public class ChatClient {

	public static void main(String[] args) {
		new MyFrame();

	}

}

class MyFrame extends Frame {
	TextField tf;
	TextArea ta;
	Socket s = null;
	DataOutputStream dos = null ;
	DataInputStream dis = null;
	boolean connected = false;
	Thread recvThread = new Thread(new RecvThread());

	MyFrame() {
		setSize(300, 300);
		setLocation(400, 300);
		tf = new TextField();
		ta = new TextArea();
		add(tf, BorderLayout.SOUTH);
		add(ta, BorderLayout.NORTH);
		pack();
		tf.addActionListener(new TextFieldListener());
		addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				disconnect();
				setVisible(false);
				System.exit(0);
			}
		});
		setVisible(true);
		connect();
		recvThread.start();
		
	}
	
	
	private class RecvThread implements Runnable {

		public void run() {
			try {
				while(connected) {	
					ta.setText(ta.getText()+dis.readUTF()+"\n");
				}
			}catch (IOException e1) {
				System.out.println("disconnected!");
			}finally {
					try {
						if(dos != null) dos.close();
						if(dis != null) dis.close();
						if(s != null) s.close();
						connected = false;
					} catch (IOException e1) {
						e1.printStackTrace();
					}
			}
		}
		
	}

	public void connect() {

		try {
			s = new Socket("127.0.0.1", 6666);
			dos = new DataOutputStream(s.getOutputStream());
			dis = new DataInputStream(s.getInputStream());
			connected = true;
			System.out.println("connected!");
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void disconnect() {
		try {
			dos.close();
			dis.close();
			s.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

	private class TextFieldListener implements ActionListener {

		public void actionPerformed(ActionEvent e) {
			String str = tf.getText().trim();
			//ta.setText(str);
			tf.setText("");
			try {
				
				dos.writeUTF(str);
				dos.flush();
				//dos.close();
			}catch(IOException e1) {
				e1.printStackTrace();
			}
		}

	}

}

